"""
LangChain 股票分析智能体协作系统 - 兼容版主程序
支持传统模式和 LangChain 模式
"""
from agent_flow import AgentFlow, LangChainAgentFlow
from dotenv import load_dotenv
from colorama import init, Fore, Style
import json
import os

def check_api_keys():
    """检查所有需要的 API 密钥是否已配置"""
    load_dotenv()
    
    try:
        with open("config.json", "r", encoding="utf-8") as f:
            config = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        print(Fore.RED + "❌ 错误: config.json 文件丢失或格式错误。")
        return False

    # 检查 Tushare Token
    tushare_token = config.get("tushare_token") or os.getenv("TUSHARE_TOKEN")
    if not tushare_token or tushare_token == "your_tushare_token_here":
        print(Fore.RED + "❌ 错误: Tushare Token 未配置。请在 config.json 或 .env 文件中设置。")
        return False

    # 检查所有智能体的 app_key
    agents_config = config.get("agents", {})
    for agent_name, agent_info in agents_config.items():
        api_key = agent_info.get("app_key") or os.getenv(f"{agent_name.upper()}_API_KEY") or os.getenv("OPENAI_API_KEY")
        if not api_key or "your_" in api_key:
            print(Fore.RED + f"❌ 错误: 智能体 '{agent_name}' 的 API Key (app_key) 未配置。")
            return False

    return True

def check_langchain_availability():
    """检查 LangChain 是否可用"""
    try:
        import langchain_core
        import langchain_openai
        return True
    except ImportError:
        return False

def select_mode():
    """选择运行模式"""
    langchain_available = check_langchain_availability()
    
    print(Fore.CYAN + "\n🤖 请选择运行模式:")
    
    if langchain_available:
        print(Fore.GREEN + "1. 🚀 LangChain 模式 (推荐) - 展示 LangChain 完整功能")
        print(Fore.YELLOW + "2. 🔄 兼容模式 - 传统智能体协作")
        
        choice = input(Fore.CYAN + "\n请输入选项 (1-2): ").strip()
        
        if choice == "1":
            return "langchain"
        elif choice == "2":
            return "compatible"
        else:
            print(Fore.YELLOW + "使用默认 LangChain 模式...")
            return "langchain"
    else:
        print(Fore.YELLOW + "⚠️ LangChain 未安装，使用兼容模式")
        print(Fore.CYAN + "如需使用 LangChain 功能，请运行: pip install -r requirements.txt")
        return "compatible"

def run_langchain_mode(stock_code: str):
    """运行 LangChain 模式"""
    print(Fore.CYAN + Style.BRIGHT + "\n🚀 启动 LangChain 智能体协作模式")
    print(Fore.CYAN + "=" * 50)
    
    try:
        agent_flow = LangChainAgentFlow()
        agent_flow.run(stock_code)
    except Exception as e:
        print(Fore.RED + f"\n❌ LangChain 模式运行失败: {e}")
        print(Fore.YELLOW + "尝试切换到兼容模式...")
        run_compatible_mode(stock_code)

def run_compatible_mode(stock_code: str):
    """运行兼容模式"""
    print(Fore.CYAN + Style.BRIGHT + "\n🔄 启动兼容智能体协作模式")
    print(Fore.CYAN + "=" * 50)
    
    try:
        agent_flow = AgentFlow()
        agent_flow.run(stock_code)
    except Exception as e:
        print(Fore.RED + f"\n❌ 兼容模式运行失败: {e}")

def main():
    """主函数"""
    init(autoreset=True)
    
    print(Fore.CYAN + Style.BRIGHT + "🤖 LangChain 股票分析智能体协作系统")
    print(Fore.CYAN + "=" * 50)
    print(Fore.CYAN + "🔥 展示 LangChain 核心功能和最佳实践")

    # 检查配置
    if not check_api_keys():
        print(Fore.YELLOW + "\n⚠️ 请检查并配置好所有 API 密钥后再运行。")
        print(Fore.CYAN + "📖 配置说明请参考 README.md")
        return

    print(Fore.GREEN + "\n✅ API 密钥配置检查通过")

    # 选择运行模式
    mode = select_mode()
    
    try:
        # 获取股票代码
        print(Fore.CYAN + f"\n📈 股票分析设置:")
        stock_code = input(Fore.GREEN + "请输入股票代码 (例如: 600519.SH，直接回车使用默认): ").strip()
        
        if not stock_code:
            stock_code = "600519.SH"  # 贵州茅台
            print(Fore.CYAN + f"使用默认股票代码: {stock_code} (贵州茅台)")

        # 根据模式运行
        if mode == "langchain":
            run_langchain_mode(stock_code)
        else:
            run_compatible_mode(stock_code)

        print(Fore.CYAN + Style.BRIGHT + "\n🎉 程序执行完成！")
        
        # 提示其他功能
        print(Fore.CYAN + "\n💡 更多功能:")
        print(Fore.YELLOW + "- 运行 python main_langchain.py 体验完整 LangChain 功能")
        print(Fore.YELLOW + "- 运行 python test_langchain_demo.py 进行系统测试")

    except KeyboardInterrupt:
        print(Fore.YELLOW + "\n\n👋 用户中断，程序退出")
    except Exception as e:
        print(Fore.RED + f"\n❌ 程序运行期间发生意外错误: {e}")

if __name__ == "__main__":
    main()

